package com.cheetah.seckill.web;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.api.R;
import com.cheetah.seckill.entity.Order;
import com.cheetah.seckill.service.SeckillService;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 测试用的。
 */
@RestController
@RequestMapping("/test/seckill")
public class SeckillTestController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private SeckillService seckillService;
    private final static Logger LOGGER = LoggerFactory.getLogger(SeckillTestController.class);

    private static int corePoolSize = Runtime.getRuntime().availableProcessors();
    /**
     * 创建线程池  调整队列数 拒绝服务
     */
    private static ThreadPoolExecutor executor  = new ThreadPoolExecutor(corePoolSize, corePoolSize+1, 10L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1000));

    @RequestMapping("/start")
    public R start(long id) {
        int skillNum = 200;
        this.seckillService.deleteSeckill(id);
        final CountDownLatch latch = new CountDownLatch(skillNum);
        for(int i=0;i<skillNum;i++){
            Runnable task = () -> {
                Order order = newOrder(id);

                this.rocketMQTemplate.convertAndSend("topic_order", order);
                latch.countDown();
            };
            executor.execute(task);
        }
        try {
            latch.await();// 等待所有人任务结束
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return R.ok("秒杀成功");
    }

    Order newOrder(long id) {
        Order order = new Order();
        order.setId(IdWorker.getId());
        order.setSeckillId(id);
        return order;
    }
}
